package com.easepal7506a.project.ui.presenter;


import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.easepal.socketiolib.model.SocketModel;
import com.easepal7506a.project.Constant.CommmandNum;
import com.easepal7506a.project.manager.DataManager;
import com.easepal7506a.project.network.CommondManager;
import com.easepal7506a.project.observer.SocketDataObserver;
import com.easepal7506a.project.observer.TimeObserver;
import com.easepal7506a.project.ui.iview.IHomeView7506;
import com.ogawa.base.callback.GetOnlineCallback;
import com.ogawa.base.callback.GetStateCallback;
import com.ogawa.base.callback.GetTokenCallback;
import com.ogawa.base.network.BaseResponse;
import com.ogawa.base.network.bean.BeanOnline;
import com.ogawa.base.network.bean.BeanStateInfo;
import com.ogawa.base.network.bean.BeanToken;
import com.ogawa.base.utils.CommonUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by FHB on 2018/4/1.
 */

public class HomePresenter7506 implements SocketDataObserver.SocketReceive {
    IHomeView7506 mView;
    private Disposable mDisposable;
    private Disposable mDisposableRunning;
    private boolean hasChange;
    public HomePresenter7506(IHomeView7506 view) {
        mView = view;
        SocketDataObserver.getInst().registerObserver(this);
    }
    //3
    public void getToken(){
        Log.e("SockeStatus_Home1","token==getToken");

        CommondManager.getInst().getToken(DataManager.getInst().getmSn(), new GetTokenCallback() {
            @Override
            public void onGetTokenSuccess(BaseResponse<BeanToken> program) {
                if(program.getErrCode().equals("0")){

                    mView.getTokenSucceed(program.getData().getToken());
                    String auto = DataManager.getInst().getValue(CommmandNum.mStatusAuto);
                    String unAuto =  DataManager.getInst().getValue(CommmandNum.mStatusHand);
                    String knead=  DataManager.getInst().getValue(CommmandNum.mStatusKnead);
                    if(!auto.equals("0")){
                        toActivity(1,auto);
                    }
                    else if(!unAuto.equals("0")||!knead.equals("0")){
                        toActivity(2,"");
                    }
                }
                else {
                    mView.getTokenFail();
                }
            }

            @Override
            public void onGetTokenFailure() {
                mView.getTokenFail();
            }
        });
    }
    //重连
    public void getreconnect(){
        CommondManager.getInst().getToken(DataManager.getInst().getmSn(), new GetTokenCallback() {
            @Override
            public void onGetTokenSuccess(BaseResponse<BeanToken> program) {
                if(program.getErrCode().equals("0")){
                    mView.getTokenSucceed(program.getData().getToken());
                }
                else {

                }
            }

            @Override
            public void onGetTokenFailure() {

            }
        });
    }
    /**2
     *
     * @param isRefresh true 关机之后刷新数据
     */
    public void getDatas(final boolean isRefresh) {
        CommondManager.getInst().getState("all", new GetStateCallback() {
            @Override
            public void onGetStateSuccess(BaseResponse<BeanStateInfo> program) {
                if(program.getData().getCmdRsps()!=null){
                    DataManager.getInst().clearMap();
                    DataManager.getInst().setInitSucceed(true);
                    for(int i =0;i<program.getData().getCmdRsps().size();i++){
                        DataManager.getInst().putKeyValue(program.getData().getCmdRsps().get(i).getKey(),(program.getData().getCmdRsps().get(i).getValue()));

                    }
                    if(!isRefresh){
                        mView.initSucceed();
                    }

                }
                else {

                    if(!isRefresh){
                        mView.initFail(isRefresh,false);
                    }


                }
            }

            @Override
            public void onStateFailure() {
                if(!isRefresh){
                    mView.initFail(isRefresh,false);
                }

            }
        });
    }

    /**2
     *配网之后
     * @param
     */
    public void getDataAfterLine(boolean isRefresh,boolean isSoftAp) {
        CommondManager.getInst().getState("0B00", new GetStateCallback() {
            @Override
            public void onGetStateSuccess(BaseResponse<BeanStateInfo> program) {
                if(program.getData().getCmdRsps()!=null){
                    DataManager.getInst().clearMap();
                    DataManager.getInst().setInitSucceed(true);
                    for(int i =0;i<program.getData().getCmdRsps().size();i++){
                        DataManager.getInst().putKeyValue(program.getData().getCmdRsps().get(i).getKey(),(program.getData().getCmdRsps().get(i).getValue()));

                    }
                    if(!isRefresh){
                        mView.initSucceed();
                    }

                }
                else {
                    DataManager.getInst().setInitSucceed(false);
                    if(!isRefresh){
                        mView.initFail(isRefresh,isSoftAp);
                    }
                }
            }

            @Override
            public void onStateFailure() {
                DataManager.getInst().setInitSucceed(false);
                if(!isRefresh){
                    mView.initFail(isRefresh,isSoftAp);
                }

            }
        });
    }

    /**
     * 1
     * @param context
     * @param sn
     */
    public void getOnline(Context context, String sn){
        CommondManager.getInst().getOnline(context, sn, 0, new GetOnlineCallback() {
            @Override
            public void onGetOnlineSuccess(BaseResponse<BeanOnline> program) {
                if(program.getErrCode().equals("0")){
                    mView.getOnlineSucceed();
                }else {
                    mView.getOnlineFail();
                }
            }

            @Override
            public void onGetOnlineFailure() {
                mView.getOnlineFail();
            }
        });
    }

    @Override
    public void onRceiveSocket(SocketModel model) {
        String key = model.getKey();
        String value  = model.getValue();
        if(key.equals(CommmandNum.mStatusRunning)){
            if(value.equals("0")){
                toActivity(3,"");
            }
            if(!value.equals("3")){
                getDataAfterLine(true,false);
            }
            mView.isPause(value.equals("3"));

        }

        else if(key.equals(CommmandNum.mStatusAuto)){
            hasChange =true;
            if(!value.equals("0")){
                toActivity(1,value);
            }
        }
        else if(key.equals(CommmandNum.mStatusHand)||key.equals(CommmandNum.mStatusKnead)){
            toAdvanceActivity(value);
            hasChange =true;
        }
        else if(key.equals(CommmandNum.mStatusLed)){
            hasChange =true;
        }
        else if(key.equals(CommmandNum.mStatusJdgl)){
            hasChange =true;
        }
        else if(key.equals(CommmandNum.mStatusHot)){
            hasChange =true;
        }

        else if(key.equals(CommmandNum.mStatusAirShoulder)){
            hasChange =true;
        }

        else if(key.equals(CommmandNum.mStatusAirSit)){
            hasChange =true;
        }

        else if(key.equals(CommmandNum.mStatusAirHand)){
            hasChange =true;
        }


        else if(key.equals(CommmandNum.mStatusAirLeg)){
            hasChange =true;
        }


        else if(key.equals(CommmandNum.mStatusAirAll)){
            hasChange =true;
        }



        else if(key.equals(CommmandNum.mStatusPointPosition)){
            Log.e("mPoint",value+"");
        }
        else if(key.equals(CommmandNum.mStatusTIME)&&!TextUtils.isEmpty(value)){
            String min =value.substring(0,value.indexOf(":"));
            String sec =value.substring(value.indexOf(":")+1);
            Log.e("updatatime",min+"=="+sec);
            mView.updataTime(min,sec);
            TimeObserver.getInst().noticeTimeChange(min,sec);
        }
        if(hasChange){
            changeRunningShow();
        }

    }

    private void toAdvanceActivity( final String value){
        Observable.timer(200, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable =d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {

                        if(DataManager.getInst().getValue(CommmandNum.mStatusAuto).equals("0")&&!value.equals("0")){
                            toActivity(2,"");
                        }



                        mDisposable.dispose();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }


    private void changeRunningShow(){
        Observable.timer(400, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposableRunning =d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        if(hasChange){
                            boolean auto = DataManager.getInst().isAutoRunning();
                            boolean isAdvance = DataManager.getInst().isAdvanceRunning();
                            if(auto){
                                String name = CommonUtil.getAutoName(DataManager.getInst().getAuto());
                                mView.showRunning("正在执行专业按摩:"+name,name);
                            }else if(isAdvance){
                                mView.showRunning("正在执行高级按摩","");
                            }else {
                                mView.showRunning("","");
                            }

                            hasChange = false;

                        }



                        mDisposableRunning.dispose();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mDisposableRunning.dispose();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    /**
     *
     * @param witch  1  自动程序  2 手动程序
     * @param value
     */

    private void toActivity(int witch,String value){
        if(witch==1){
            if(!value.equals("0")){
                mView.toProMasDetailActivity(CommonUtil.getAutoName(value));
            }
        }else if(witch==2){
            mView.toProAdvanceActivity();
        }else if(witch==3){
            mView.showRunning("","");
            mView.closeOther();
        }

    }
    public void onDestory(){
        SocketDataObserver.getInst().removeObserver(this);
    }
}
